package com.dm.service.impl;

import com.dm.common.enums.ResponseCode;
import com.dm.dao.UserDao;
import com.dm.dto.ResponseDto;
import com.dm.dto.input.UserDto;
import com.dm.entity.User;
import com.dm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author hqw521@qq.com
 * @date 2018/11/15 11:36
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;

    @Override
    public ResponseDto<UserDto> login(UserDto userDto) {
        ResponseDto<UserDto> responseDto = new ResponseDto();
        Long resultCount = userDao.checkUsername(userDto.getUserName());
        if (resultCount == 0) {
            responseDto.setMsg("用户不存在");
            responseDto.setStatus(ResponseCode.ERROR.getCode());
            return responseDto;
        }
        UserDto user = userDao.selectUser(userDto);
        if (user == null) {
            responseDto.setMsg("密码错误");
            responseDto.setStatus(ResponseCode.ERROR.getCode());
            return responseDto;
        }
        responseDto.setStatus(ResponseCode.SUCCESS.getCode());
        responseDto.setData(user);
        return responseDto;
    }

    @Override
    public ResponseDto register(UserDto userDto) {
        ResponseDto responseDto = new ResponseDto();
        Long resultCount = userDao.checkUsername(userDto.getUserName());
        if (resultCount > 0) {
            responseDto.setMsg("用户已存在");
            responseDto.setStatus(ResponseCode.ERROR.getCode());
            return responseDto;
        }
        Integer result = userDao.insertUser(userDto);
        if (result <= 0) {
            responseDto.setMsg("用户新增失败");
            responseDto.setStatus(ResponseCode.ERROR.getCode());
            return responseDto;
        }
        responseDto.setMsg("用户新增成功");
        responseDto.setStatus(ResponseCode.SUCCESS.getCode());
        return responseDto;
    }

    @Override
    public ResponseDto<List<UserDto>> findAllUser() {
        ResponseDto<List<UserDto>> responseDto = new ResponseDto<>();
        List<UserDto> userDtos = userDao.findAllUser();
        responseDto.setStatus(ResponseCode.SUCCESS.getCode());
        responseDto.setData(userDtos);
        return responseDto;
    }
}
